package util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.Properties;

/**
 * 测试qq发送邮件
 */
public class EmailSender {

    private static final Logger logger = LoggerFactory.getLogger(EmailSender.class);

    public static void send(boolean isSuccess, String msg, String sendEmail) {
        if (StringUtils.isBlank(sendEmail)) {
            return;
        }
        try {
            //创建Properties 类用于记录邮箱的一些属性
            EmailProperties emailProperties = new EmailProperties();
            final Properties props = emailProperties.getProperties();
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            InternetAddress form = new InternetAddress(
                    props.getProperty("mail.user"));
            message.setFrom(form);
            // 设置收件人的邮箱
            InternetAddress to = new InternetAddress(sendEmail);
            message.setRecipient(RecipientType.TO, to);
            // 设置邮件标题
            if (isSuccess) {
                message.setSubject("成功：巨龙报工");
            } else {
                message.setSubject("失败：巨龙报工");
            }
            // 设置邮件的内容体
            message.setContent(msg, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
            logger.info("QQ邮件发送完毕!");
        } catch (MessagingException e2) {
            logger.warn("邮件发送失败", e2);
        }
    }

    public static void main(String[] args) {
        send(true,"ff","943034773@qq.com");
    }
}
